package com.kczd.jinlan.view.classify.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.kczd.jinlan.R;
import com.kczd.jinlan.adapter.TextAdapter;
import com.kczd.jinlan.myview.MyclassListView;
import com.kczd.jinlan.utils.Config;
import com.kczd.jinlan.view.classify.FoodDetailsActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * yang_g
 * 分类模块
 * Created by Administrator on 2017/5/15.
 */

public class ClassificationFragment extends Fragment {

    private static final String TAG="ClassificationFragment.class";
    String url = Config.net_addr + "index/category";
    private View view;

    //省的listView
    private MyclassListView listView1;
    private TextAdapter mAdapter1;
    //市的listView
    private MyclassListView listView2;
    private TextAdapter mAdapter2;
    //区的listView
    private MyclassListView listView3;
    private TextAdapter mAdapter3;

    //当前省市区的选中位置
    public int provincePosition;
    public int cityPosition;
    public int areasPosition;
    //最终选中的省,市，区
    private String province;
    private String provinceid;
    private String city;
    private String cityid;
    private String area;
    private String areaid;

    /**
     * 所有省
     */
    private String[] mProvinceDatas;
    private String[] mProvinceDatasid;
    /**
     * key - 省 value - 市s
     */
    private Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    private Map<String, String[]> mCitisDatasMapid = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区s
     */
    private Map<String, String[]> mAreaDatasMap = new HashMap<String, String[]>();
    private Map<String, String[]> mAreaDatasMapid = new HashMap<String, String[]>();
    //当前的citys
    private String []citys;
    private String []citysid;
    //当前的areas
    private String []areas;
    private String []areasid;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.search_class_listviews,null);


        new Thread(new Runnable() {
            @Override
            public void run() {
                getClassifyDate();
            }
        }).start();
        return view;
    }

    private void initView() {

        listView1= (MyclassListView) view.findViewById(R.id.listview1);
        listView2=(MyclassListView) view.findViewById(R.id.listview2);
        listView3=(MyclassListView) view.findViewById(R.id.listview3);

        mAdapter1=new TextAdapter(mProvinceDatas,getActivity());
        listView1.setAdapter(mAdapter1);
        //设置city的默认值
        selectCityDefult();
        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {


                provincePosition = position;
                mAdapter1.setSelectedPosition(provincePosition);
                mAdapter1.notifyDataSetInvalidated();

                citys = mCitisDatasMap.get(mProvinceDatas[provincePosition]);
                citysid=mCitisDatasMapid.get(mProvinceDatasid[provincePosition]);

                mAdapter2 = new TextAdapter(citys, getActivity());

                listView2.setAdapter(mAdapter2);
                mAdapter2.setSelectedPosition(0);

                listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        cityPosition = position;
                        mAdapter2.setSelectedPosition(cityPosition);
                        mAdapter2.notifyDataSetInvalidated();

                        areas = mAreaDatasMap.get(citys[cityPosition]);
                        areasid=mAreaDatasMapid.get(citysid[cityPosition]);
                        mAdapter3 = new TextAdapter(areas, getActivity());
                        mAdapter3.setSelectedPosition(0);
                        listView3.setAdapter(mAdapter3);
                    }
                });
                areas = mAreaDatasMap.get(citys[0]);
                areasid = mAreaDatasMapid.get(citysid[0]);
                mAdapter3 = new TextAdapter(areas, getActivity());
                mAdapter3.setSelectedPosition(0);
                listView3.setAdapter(mAdapter3);

            }
        });
    }
    private void selectCityDefult() {
        //-------------------------------------------------------------------
        provincePosition=0;
        mAdapter1.setSelectedPosition(0);
        mAdapter1.notifyDataSetInvalidated();

        citys=mCitisDatasMap.get(mProvinceDatas[0]);
        citysid=mCitisDatasMapid.get(mProvinceDatasid[0]);
        cityPosition=0;
        mAdapter2=new TextAdapter(citys,getActivity());
        mAdapter2.setSelectedPosition(0);
        listView2.setAdapter(mAdapter2);

        listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                cityPosition = position;
                mAdapter2.setSelectedPosition(cityPosition);
                mAdapter2.notifyDataSetInvalidated();

                areas = mAreaDatasMap.get(citys[cityPosition]);
                areasid = mAreaDatasMapid.get(citysid[cityPosition]);
                mAdapter3 = new TextAdapter(areas,getActivity());

                listView3.setAdapter(mAdapter3);
            }
        });
        areasPosition=0;
        areas =mAreaDatasMap.get(citys[0]);
        areasid=mAreaDatasMapid.get(citysid[0]);
        mAdapter3 =new TextAdapter(areas,getActivity());
        mAdapter3.setSelectedPosition(0);
        listView3.setAdapter(mAdapter3);

        listView3.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent,
                                    View view, int position, long id) {
                areasPosition=position;
                province=mProvinceDatas[position];
                provinceid=mProvinceDatasid[position];
                mAdapter3.setSelectedPosition(areasPosition);
                mAdapter3.notifyDataSetInvalidated();
                //position为最后一个数组的position
//                Toast.makeText(context,
//                        "provincePosition=" + provincePosition + "cityPosition=" + cityPosition + "areasPosition=" + areasPosition,
//                        Toast.LENGTH_LONG).show();
                province=mProvinceDatas[provincePosition];
                provinceid=mProvinceDatasid[provincePosition];

                city =mCitisDatasMap.get(province)[cityPosition];
                cityid=mCitisDatasMapid.get(provinceid)[cityPosition];

                area =mAreaDatasMap.get(city)[areasPosition];
                areaid=mAreaDatasMapid.get(cityid)[areasPosition];
//                textBack.textback(province,city,area);
               Log.e("zhangaizhang",provinceid+"=="+cityid+"=="+areaid);
                Intent intent=new Intent(getActivity(), FoodDetailsActivity.class);
                intent.putExtra("position",areaid);
                startActivity(intent);
            }
        });
    }

    //获取数据
    public void  getClassifyDate()
    {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder()
                .build();
        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response=client.newCall(request).execute();
            String strResult=response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            handler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG,val);
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(Config.code.equals(jsonResult.getString("code"))) {

                    JSONArray jsonArray= jsonResult.getJSONArray("data");
                    mProvinceDatas = new String[jsonArray.length()];
                    mProvinceDatasid = new String[jsonArray.length()];
                    for(int i=0;i<jsonArray.length();i++)
                    {
                        JSONObject jsonp=jsonArray.getJSONObject(i);

                        String province=jsonp.getString("name");//一级菜单name
                        String provinceid=jsonp.getString("id");
                        mProvinceDatas[i] = province;
                        mProvinceDatasid[i]=provinceid;

                        JSONArray jsonCs = null;
                        try
                        {
                            /**
                             * Throws JSONException if the mapping doesn't exist or is
                             * not a JSONArray.
                             */
                            jsonCs=jsonp.getJSONArray("tmenu");
                        } catch (Exception e1)
                        {
                            continue;
                        }
                        String[] mCitiesDatas = new String[jsonCs.length()];
                        String[] mCitiesDatasid = new String[jsonCs.length()];
                        for(int j=0;j<jsonCs.length();j++)
                        {
                            String city=jsonCs.getJSONObject(j).getString("name");
                            String id1=jsonCs.getJSONObject(j).getString("id");
                            mCitiesDatasid[j]=id1;
                            mCitiesDatas[j] = city;

                            JSONArray jsonAreas = null;
                            try
                            {
                                /**
                                 * Throws JSONException if the mapping doesn't exist or
                                 * is not a JSONArray.
                                 */
                                jsonAreas = jsonCs.getJSONObject(j).getJSONArray("sub_menu");

                            } catch (Exception e)
                            {
                                continue;
                            }

                            String[] mAreasDatas = new String[jsonAreas.length()];// 当前市的所有区
                            String[] mAreasDatasid = new String[jsonAreas.length()];// 当前市的所有区
                            for(int z=0;z<jsonAreas.length();z++)
                            {
                                String area=jsonAreas.getJSONObject(z).getString("name");
                                String id2=jsonAreas.getJSONObject(z).getString("id");
                                mAreasDatas[z]=area;
                                mAreasDatasid[z]=id2;
                            }
                            mAreaDatasMap.put(city, mAreasDatas);
                            mAreaDatasMapid.put(id1,mAreasDatasid);
                        }
                        mCitisDatasMap.put(province, mCitiesDatas);
                        mCitisDatasMapid.put(provinceid, mCitiesDatasid);
                    }
                    initView();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
}
